package cn.bugstack.trigger.listener;

import cn.bugstack.domain.trade.model.valobj.TeamRefundSuccess;
import cn.bugstack.domain.trade.service.ITradeRefundOrderService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author lxz
 * @description 结算完成消息监听
 * @create 2025-03-08 13:49
 */
@Slf4j
@Component
public class RefundSuccessTopicListener {

    @Resource
    private ITradeRefundOrderService tradeRefundOrderService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "${spring.rabbitmq.config.producer.topic_team_refund.queue}"),
                    exchange = @Exchange(value = "${spring.rabbitmq.config.producer.exchange}", type = ExchangeTypes.TOPIC),
                    key = "${spring.rabbitmq.config.producer.topic_team_refund.routing_key}"
            )
    )
    public void listener(String message) {
        log.info("接收消息（退单成功）:{}", message);
        // 手动解析并构建对象
        JSONObject jsonObject = JSON.parseObject(message);
        TeamRefundSuccess teamRefundSuccess = TeamRefundSuccess.builder()
                .activityId(jsonObject.getLong("activityId"))
                .teamId(jsonObject.getString("teamId"))
                .userId(jsonObject.getString("userId"))
                .orderId(jsonObject.getString("orderId"))
                .type(jsonObject.getString("type"))
                .build();
        try{
            tradeRefundOrderService.restoreTeamStock(teamRefundSuccess);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

}
